// app.js
import NetWork from "./config/netWork";
App({
  netWork: null,
  globalData: {
    userInfo: null,
    showToastTitle: "",
    netWorkProxy: null, // 用于存储 Proxy 拦截器
    networkStatus: {
      isConnected: true, // 默认有网络
      networkType: "wifi", // 默认网络类型
    },
  },

  onLaunch() {
    console.log("App Launch========");
    // this.initNetworkListener();
  },

  onShow () {
    if(this.netWork){
      this.netWork.destroy();
    }
    this.netWork = new NetWork();
    console.log("App show========");
  },
  onHide () {
    this.netWork.destroy();
    this.netWork = null;
    console.log("App Hide========");
  },
  // 初始化网络监听
  initNetworkListener() {
    const app = this;

    // 1. 监听网络状态变化
    wx.onNetworkStatusChange((res) => {
      console.log("网络状态变化:", res);
      app.updateNetworkStatus(res.isConnected, res.networkType);
    });

    // 2. 获取初始网络状态
    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType || "unknown";
        const isConnected = networkType !== "none";
        app.updateNetworkStatus(isConnected, networkType);
      },
    });
  },

  // 更新网络状态（并触发回调）
  updateNetworkStatus(isConnected, networkType) {
    this.globalData.networkStatus = { isConnected, networkType };

    // 如果有页面注册了回调，则执行
    if (this.globalData.netWorkProxy) {
      this.globalData.netWorkProxy.triggerNetworkChange(this.globalData.networkStatus);
    }
  },

  // 提供给页面的网络拦截器
  netWorkCallback: function (callback) {
    const app = getApp();
    const handler = {
      // 拦截网络变化
      triggerNetworkChange(isConnected, networkType) {
        if (typeof callback === "function") {
          callback(isConnected, networkType);
        }
      },
    };

    // 存储 Proxy 对象（可选）
    this.globalData.netWorkProxy = new Proxy(handler, {});
  },
});